package com.financial.service.yspay.service.impl;

import com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.FinancialYsWithdrawalService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Davidbieber
 * @description 银盛提现业务实现类
 * @email davidbieber@163.com
 * @date 2019/11/19 10:31 AM
 */
@Service
public class FinancialYsWithdrawalServiceImpl implements FinancialYsWithdrawalService {
    protected static final Logger logger = LoggerFactory.getLogger(FinancialYsWithdrawalServiceImpl.class);

    @Value("${ysWithdrawalNotifyUrl}")
    private String ysWithdrawalNotifyUrl;

    @Value("${ysWithdrawalMethod}")
    private String ysWithdrawalMethod;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Override
    public ApiResult ysWithdrawal(String requestParam) {
        logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()------银盛提现请求参数json为:" + requestParam);
        String ysWithdrawalJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsWithdrawalDTO =JsonUtils.parseObject(ysWithdrawalJson);
        /*返回内容初始化*/
        String content = null;
        if (financialYsWithdrawalDTO != null) {
            /*组装银盛微信支付参数信息*/
            Map<String, String> param = new HashMap<>();
            param.put("method", ysWithdrawalMethod);
            param.put("partner_id", financialYsWithdrawalDTO.getPARTNER_ID());
            param.put("timestamp", DateUtils.getNowTimeStr());
            param.put("charset", financialYsWithdrawalDTO.getDEFAULT_CHARSET());
            param.put("sign_type", financialYsWithdrawalDTO.getSIGN_ALGORITHM());
            param.put("notify_url", ysWithdrawalNotifyUrl);
            param.put("version", financialYsWithdrawalDTO.getVERSION());
            /*获取biz_content业务参数信息*/
            param.put("biz_content", requestParam);
            logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()----->请求银盛提现参数为:"+param.toString());
            try {
                //签名
                Map<String, String> sPara = financialYsPayBuildRequestParaService.buildRequestPara(param, financialYsWithdrawalDTO);
                //发起请求
                logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()----->签名完成的参数："+JsonUtils.objectToJson(sPara));
                String returnString = HttpUtils.httpsSend(financialYsWithdrawalDTO.getYSEPAY_GATEWAY_URL_DSF(), sPara);
                //回执参数JSON转map
                Map resultMap = (Map) JSON.parse(returnString);
                Map<String, String> obj = (Map<String, String>) resultMap.get("ysepay_merchant_withdraw_quick_accept_response");
                boolean verifyResult = false;
                if (obj == null) {
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                int begin = returnString.indexOf("ysepay_merchant_withdraw_quick_accept_response");
                content = returnString.substring(begin);
                content = content.replace("ysepay_merchant_withdraw_quick_accept_response", "");
                content = content.substring(2, content.length() - 1);
                verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), content, "utf-8", financialYsWithdrawalDTO);
                logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()----->提现请求回执信息,验签是否成功content:"+content+"验签结果verifyResult--"+verifyResult);
                if (null == content || content.equals("")) {
                    logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()----->验签没有成功:银盛返回结果为空");
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                /*解析contrent*/
                Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
                boolean tradeStatus = contentMap.containsKey("trade_status");
                logger.info("FinancialYsWithdrawalServiceImpl.ysWithdrawal()----->提现通知成功是否包含trade_status"+tradeStatus);
                if(tradeStatus){
                    Object tempParams = contentMap.get("trade_status");
                    String returnTradeStatus = tempParams == null ? null : tempParams.toString();
                    if(returnTradeStatus.equalsIgnoreCase(YsServiceEnumConstants.ENUM_TRADE_STATUS)){
                        /*TRADE_ACCEPT_SUCCESS是预提现成功标识*/
                        return ApiResult.success(content);
                    }else{
                        /*失败返回*/
                        return ApiResult.failure(content);
                    }
                }else{
                    /*失败返回*/
                    return ApiResult.failure(content);
                }
            } catch (IOException e) {
                logger.error("银盛提现查询接口" + e.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e1) {
                logger.error("银盛提现查询接口" + e1.getMessage());
                e1.printStackTrace();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return ApiResult.failure(content);
    }
}
